<template>
  <div class="userinfo-container">
    <div class="user-header">
      <div class="user-avatar">
        <el-avatar :size="80" :src="userInfo.avatar">
          {{ userInfo.username && userInfo.username.charAt(0).toUpperCase() }}
        </el-avatar>
      </div>
      <div class="user-details">
        <h1 class="username">{{ userInfo.username || "未知用户" }}</h1>
        <div class="user-stats">
          <div class="stat-item">
            <span class="stat-value">{{ userInfo.totalGames || 0 }}</span>
            <span class="stat-label">游戏总数</span>
          </div>
          <div class="stat-item">
            <span class="stat-value">{{ formatTotalTime(userInfo.totalPlayTime || 0) }}</span>
            <span class="stat-label">总游戏时长</span>
          </div>
          <div class="stat-item">
            <span class="stat-value">{{ userInfo.level || 0 }}</span>
            <span class="stat-label">用户等级</span>
          </div>
          <div class="stat-item">
            <span class="stat-value">
              {{ userInfo.averageRating ? userInfo.averageRating.toFixed(1) : "0.0" }}
            </span>
            <span class="stat-label">平均评分</span>
          </div>
        </div>
      </div>
    </div>

    <div class="content-section">
      <div class="section-header">
        <h2>游戏统计</h2>
        <div class="header-actions">
          <el-input
            v-model="searchQuery"
            placeholder="搜索游戏"
            prefix-icon="el-icon-search"
            clearable
            @clear="handleClear"
          />
          <el-select v-model="sortBy" placeholder="排序方式" @change="handleSortChange">
            <el-option label="按游戏时长" value="playTime" />
            <el-option label="按最近游玩" value="lastPlayed" />
            <el-option label="按游戏名称" value="name" />
          </el-select>
        </div>
      </div>

      <el-tabs v-model="activeTab" @tab-click="handleTabChange">
        <el-tab-pane label="全部游戏" name="all"></el-tab-pane>
        <el-tab-pane label="最近游玩" name="recent"></el-tab-pane>
        <el-tab-pane label="收藏游戏" name="favorites"></el-tab-pane>
      </el-tabs>

      <div v-if="filteredGames.length === 0" class="empty-state">
        <el-empty description="暂无游戏记录"></el-empty>
      </div>

      <el-table
        v-else
        :data="paginatedGames"
        stripe
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      >
        <el-table-column label="游戏" min-width="240">
          <template #default="scope">
            <div class="game-info">
              <div
                class="game-icon"
                :style="{ backgroundColor: getGameColor(scope.row.gameType || 'default') }"
              >
                {{ (scope.row.name && scope.row.name.charAt(0)) || "?" }}
              </div>
              <div class="game-details">
                <div class="game-name">{{ scope.row.name || "未知游戏" }}</div>
                <div class="game-type">{{ getGameTypeName(scope.row.gameType || "default") }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="playTime" label="游戏时长" min-width="120">
          <template #default="scope">
            {{ formatTime(scope.row.playTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="lastPlayed" label="最近游玩" min-width="160">
          <template #default="scope">
            {{ formatDate(scope.row.lastPlayed) }}
          </template>
        </el-table-column>
        <el-table-column label="游戏进度" min-width="200">
          <template #default="scope">
            <el-progress
              :percentage="scope.row.progress"
              :color="getProgressColor(scope.row.progress)"
            ></el-progress>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="startGame(scope.row)">
              开始游戏
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-if="filteredGames.length > pageSize"
          background
          layout="prev, pager, next"
          :total="filteredGames.length"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handlePageChange"
        />
      </div>

      <div class="achievements-section">
        <h2>游戏成就</h2>
        <div class="achievements-list">
          <div v-for="(achievement, index) in achievements" :key="index" class="achievement-card">
            <div class="achievement-icon" :class="{ unlocked: achievement.unlocked }">
              <i :class="achievement.icon || 'el-icon-trophy'"></i>
            </div>
            <div class="achievement-info">
              <div class="achievement-name">{{ achievement.name }}</div>
              <div class="achievement-desc">{{ achievement.description }}</div>
              <div v-if="achievement.unlocked" class="achievement-date">
                获得于 {{ formatDate(achievement.unlockedDate || achievement.unlocked_date) }}
              </div>
            </div>
          </div>
          <div v-if="achievements.length === 0" class="empty-achievements">
            <el-empty description="暂无成就记录"></el-empty>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { useRoute, useRouter } from "vue-router";
import UserGameAPI, {
  type GameUserInfo,
  type GameUserRecord,
  type GameAchievement,
} from "@/api/game/userinfo";

const route = useRoute();
const router = useRouter();
const userId = computed(() => {
  // 尝试从路由params获取ID
  const idFromParams = route.params.id ? Number(route.params.id) : undefined;
  // 兼容从query获取ID的方式，向下兼容
  const idFromQuery = route.query.id ? Number(route.query.id) : undefined;

  // 优先使用params中的ID，如果没有则使用query中的ID
  const id = idFromParams || idFromQuery;

  console.log("详情页面获取到路由参数 - params ID:", idFromParams, "query ID:", idFromQuery);
  return id;
});

// 用户信息
const userInfo = reactive<GameUserInfo>({
  id: 0,
  username: "",
  avatar: "",
  level: 0,
  totalGames: 0,
  totalPlayTime: 0,
  lastActive: "",
  activityLevel: "medium",
  achievementCount: 0,
  gamePreferences: [],
  points: 0,
  averageRating: 0,
});

// 游戏记录
const gameRecords = ref<GameUserRecord[]>([]);

// 成就列表
const achievements = ref<GameAchievement[]>([]);

// 加载状态
const loading = ref(false);

// 加载用户信息
const loadUserInfo = async () => {
  if (!userId.value) {
    ElMessage.warning("未获取到用户ID");
    return;
  }

  loading.value = true;
  try {
    // 加载用户基本信息
    try {
      const response = await UserGameAPI.getUserInfo(userId.value);
      if (response) {
        // 将返回数据映射到userInfo上
        Object.assign(userInfo, response);
        console.log("用户详情数据加载成功:", userInfo);
      }
    } catch (error) {
      console.error("加载用户基本信息失败:", error);
      ElMessage.warning("加载用户基本信息失败");
    }

    // 加载用户成就信息（单独try-catch以防止一个接口失败影响其他数据加载）
    try {
      const achievementsResponse = await UserGameAPI.getUserAchievements(userId.value);
      console.log("成就数据响应:", achievementsResponse);

      if (achievementsResponse && achievementsResponse.data) {
        achievements.value = achievementsResponse.data;
        console.log("用户成就数据加载成功:", achievements.value);
      } else if (Array.isArray(achievementsResponse)) {
        // 处理直接返回数组的情况
        achievements.value = achievementsResponse;
        console.log("用户成就数据(数组格式)加载成功:", achievements.value.length);
      } else {
        console.warn("成就数据格式异常:", achievementsResponse);
        achievements.value = []; // 设置为空数组
      }
    } catch (error) {
      console.error("加载用户成就失败:", error);
      achievements.value = []; // 设置为空数组
    }

    // 加载用户游戏记录（单独try-catch以防止一个接口失败影响其他数据加载）
    try {
      const gameRecordsResponse = await UserGameAPI.getUserGameRecords({
        pageNum: 1,
        pageSize: 100,
        userId: userId.value,
      });

      if (gameRecordsResponse && gameRecordsResponse.data) {
        // 优先使用data.records或data.list
        if (gameRecordsResponse.data.records) {
          gameRecords.value = gameRecordsResponse.data.records;
        } else if (gameRecordsResponse.data.list) {
          gameRecords.value = gameRecordsResponse.data.list;
        } else if (Array.isArray(gameRecordsResponse.data)) {
          gameRecords.value = gameRecordsResponse.data;
        }
        console.log("用户游戏记录加载成功:", gameRecords.value.length);
      }
    } catch (error) {
      console.error("加载用户游戏记录失败:", error);
      gameRecords.value = []; // 设置为空数组
    }

    ElMessage.success("用户游戏数据加载完成");
  } catch (error) {
    console.error("加载用户信息失败:", error);
    ElMessage.error("加载用户信息失败");
  } finally {
    loading.value = false;
  }
};

// 分页相关
const currentPage = ref(1);
const pageSize = ref(5);

// 筛选和排序相关
const activeTab = ref("all");
const searchQuery = ref("");
const sortBy = ref("lastPlayed");

// 根据标签、搜索和排序筛选游戏
const filteredGames = computed(() => {
  // 先根据标签筛选
  let result = [...gameRecords.value];

  if (activeTab.value === "recent") {
    // 最近7天玩过的游戏
    const oneWeekAgo = new Date();
    oneWeekAgo.setDate(oneWeekAgo.getDate() - 7);
    result = result.filter((game) => new Date(game.lastPlayed) >= oneWeekAgo);
  } else if (activeTab.value === "favorites") {
    // 收藏的游戏
    result = result.filter((game) => game.favorite);
  }

  // 再根据搜索筛选
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    result = result.filter(
      (game) =>
        game.name.toLowerCase().includes(query) ||
        getGameTypeName(game.gameType).toLowerCase().includes(query)
    );
  }

  // 最后排序
  result.sort((a, b) => {
    if (sortBy.value === "playTime") {
      return b.playTime - a.playTime;
    } else if (sortBy.value === "lastPlayed") {
      return new Date(b.lastPlayed).getTime() - new Date(a.lastPlayed).getTime();
    } else if (sortBy.value === "name") {
      return a.name.localeCompare(b.name);
    }
    return 0;
  });

  return result;
});

// 分页后的游戏列表
const paginatedGames = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredGames.value.slice(start, end);
});

// 处理页面切换
const handlePageChange = (page) => {
  currentPage.value = page;
};

// 处理标签切换
const handleTabChange = () => {
  currentPage.value = 1; // 重置到第一页
};

// 处理排序改变
const handleSortChange = () => {
  currentPage.value = 1; // 重置到第一页
};

// 处理清除搜索
const handleClear = () => {
  searchQuery.value = "";
  currentPage.value = 1;
};

// 格式化时间
const formatTime = (seconds) => {
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);

  if (hours > 0) {
    return `${hours}小时${minutes}分钟`;
  }
  return `${minutes}分钟`;
};

// 格式化总时间
const formatTotalTime = (seconds) => {
  const hours = Math.floor(seconds / 3600);
  return `${hours}小时`;
};

// 格式化日期
const formatDate = (date) => {
  if (!date) return "-";

  const d = new Date(date);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, "0");
  const day = String(d.getDate()).padStart(2, "0");

  return `${year}-${month}-${day}`;
};

// 获取游戏类型颜色
const getGameColor = (type) => {
  const colors = {
    shooting: "#e74c3c",
    rpg: "#3498db",
    strategy: "#f39c12",
    casual: "#9b59b6",
    default: "#2ecc71",
  };

  return colors[type] || colors.default;
};

// 获取游戏类型名称
const getGameTypeName = (type) => {
  const types = {
    shooting: "射击游戏",
    rpg: "角色扮演",
    strategy: "策略游戏",
    casual: "休闲游戏",
    default: "其他游戏",
  };

  return types[type] || types.default;
};

// 获取进度条颜色
const getProgressColor = (progress) => {
  if (progress < 30) return "#909399";
  if (progress < 70) return "#e6a23c";
  return "#67c23a";
};

// 开始游戏
const startGame = (game) => {
  ElMessage.success(`正在启动游戏：${game.name}`);
  // 这里可以添加跳转到游戏页面的逻辑
};

// 默认头像
const defaultAvatar = "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png";

// 组件挂载时加载数据
onMounted(() => {
  console.log("详情页面挂载，路由参数:", route.query);

  if (userId.value) {
    console.log("开始加载用户详情数据，用户ID:", userId.value);
    loadUserInfo();
  } else {
    console.warn("未获取到有效的用户ID，请从用户列表点击进入");
    ElMessage.warning("未获取到用户ID，请从用户列表点击进入");
    setTimeout(() => {
      router.push("/userinfo/list");
    }, 2000);
  }
});
</script>

<style scoped>
.userinfo-container {
  padding: 20px;
  background-color: #f8f9fa;
  min-height: calc(100vh - 80px);
}

.user-header {
  display: flex;
  align-items: center;
  padding: 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.user-avatar {
  margin-right: 30px;
}

.user-details {
  flex: 1;
}

.username {
  margin: 0 0 15px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.user-stats {
  display: flex;
  gap: 30px;
}

.stat-item {
  display: flex;
  flex-direction: column;
}

.stat-value {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.content-section {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  padding: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 15px;
}

.game-info {
  display: flex;
  align-items: center;
}

.game-icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 18px;
  font-weight: bold;
  margin-right: 15px;
}

.game-details {
  display: flex;
  flex-direction: column;
}

.game-name {
  font-weight: 500;
  margin-bottom: 5px;
}

.game-type {
  font-size: 12px;
  color: #909399;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.achievements-section {
  margin-top: 30px;
}

.achievements-section h2 {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 20px;
}

.achievements-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.achievement-card {
  display: flex;
  padding: 15px;
  border-radius: 8px;
  background-color: #f9f9f9;
  border: 1px solid #ebeef5;
}

.achievement-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background-color: #909399;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  color: white;
  font-size: 20px;
}

.achievement-icon.unlocked {
  background-color: #67c23a;
}

.achievement-info {
  flex: 1;
}

.achievement-name {
  font-weight: 600;
  margin-bottom: 5px;
  color: #303133;
}

.achievement-desc {
  font-size: 13px;
  color: #606266;
  margin-bottom: 5px;
}

.achievement-date {
  font-size: 12px;
  color: #909399;
}

.empty-state {
  padding: 30px 0;
}

.empty-achievements {
  padding: 30px 0;
}
</style>
